# coding=utf-8

"""
    Created by Kalyter on 2017-12-15.
"""

import os

from learning.scientifc import writer
from learning.scientifc.jobs.job import Job
from learning.scientifc.readers.reader import ReaderFactory


class CACJob(Job):

    name = '计算自定义编码下的平均值，可以自定义截取长度CUT_LEN'

    def __init__(self, app):
        super().__init__(app)
        self.reader_factory = ReaderFactory(app)

    @classmethod
    def from_app(cls, app):
        return cls(app)

    def run(self):
        path = self.app.config.get('AVERAGE_PATH')
        rate_header = self.app.config.get('AVERAGE_RATE')
        reporter_header = self.app.config.get('AVERAGE_REPORTER')
        partner_header = self.app.config.get('AVERAGE_PARTNER')
        rate_name_header = self.app.config.get('AVERAGE_RATE_NAME')
        year_header = self.app.config.get('AVERAGE_YEAR')
        custom_header = self.app.config.get("AVERAGE_CUSTOM_CODE")
        cut_len = self.app.config.get('AVERAGE_CUT_LEN')
        average_header = self.app.config.get('AVERAGE_HEADER')

        headers = [path, custom_header, rate_header, reporter_header,
                   partner_header, rate_name_header, year_header, cut_len]

        if not all(headers):
            raise AttributeError("can't read config")
        else:
            files = os.listdir(path)
            for name in files:
                if '$' not in name and os.path.isfile(os.path.join(path, name)):
                    print('开始处理 %s' % name)
                    filename = os.path.join(path, name)
                    reader = self.reader_factory.create(filename)
                    rows = reader.nrows
                    headers = reader.row_values(0)
                    custom_index = headers.index(custom_header)
                    reporter_index = headers.index(reporter_header)
                    rate_name_index = headers.index(rate_name_header)
                    year_index = headers.index(year_header)
                    rate_index = headers.index(rate_header)
                    partner_index = headers.index(partner_header)

                    data = {}
                    for row in range(1, rows):
                        row_data = reader.row_values(row)
                        code_value = row_data[custom_index]
                        code_value = str(code_value)[:cut_len]
                        reporter = row_data[reporter_index]
                        partner = row_data[partner_index]
                        init_item = {
                            'code': code_value,
                            'reporter': reporter,
                            'rate_name': row_data[rate_name_index],
                            'year': int(row_data[year_index]),
                            'partner': partner,
                            'rate': []
                        }
                        code_data = data.setdefault(code_value, init_item)
                        rate = row_data[rate_index]
                        try:
                            rate = float(rate)
                        except:
                            rate = 0.0

                        code_data['rate'].append(rate)

                    write_result = [
                        ('报告国家',
                         '合作国家',
                         '编码(%s)' % average_header,
                         '平均税率',
                         '年份',
                         '税率名称')
                    ]
                    write_name = None
                    for value in data.values():
                        average_rate = float(sum(value['rate'])) / len(value['rate'])
                        item = (
                            value['reporter'],
                            value['partner'],
                            value['code'],
                            '%.2f' % average_rate,
                            value['year'],
                            value['rate_name']
                        )
                        write_result.append(item)
                        if not write_name:
                            write_name = '%s-%s-%s-%s.xls' \
                                         % (value['reporter'],
                                            value['partner'],
                                            value['year'],
                                            len(value['code']))
                    writer.write(write_result, write_name, average_header)
